package com.android.lovely.ui.dialog

import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.style.AbsoluteSizeSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.viewModels
import androidx.core.text.buildSpannedString
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.android.lovely.R
import com.android.lovely.admob.Ad
import com.android.lovely.admob.showReword
import com.android.lovely.data.SignBean
import com.android.lovely.data.SignResponse
import com.android.lovely.data.hasSignedToday
import com.android.lovely.data.isToday
import com.android.lovely.data.saveSignShowToday
import com.android.lovely.data.saveSignToday
import com.android.lovely.databinding.DialogSignBinding
import com.android.lovely.databinding.ItemDailySignBinding
import com.android.lovely.databinding.ItemDailySignLandBinding
import com.android.lovely.framework.BaseActivity
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.manager.KVStore
import com.android.lovely.ui.viewmodel.SignViewModel
import com.android.lovely.user.UserManager
import com.android.lovely.user.UserManager.registerAuthChange
import com.kotlin.extensions.context.ActivityExt.navBarHeight
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.withTimeoutOrNull
import java.util.Locale

/**
 *
 * @author why
 * @date 2025/3/25 11:38
 */
class SignDialog : BaseActivity<DialogSignBinding>() {

    private val viewModel by viewModels<SignViewModel>()
    val adapter by lazy {
        SignAdapter()
    }

    var res: SignResponse? = null

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.navBar.updateLayoutParams<MarginLayoutParams> {
            height = navBarHeight + 10.dp
        }
        mBinding.ivClose.addStatusBarMarginTop()
        mBinding.ivClose.clickable {
           finish()
        }
        mBinding.rv.layoutManager = GridLayoutManager(this, 3).apply {
            spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return if (position == 6) 3 else 1
                }
            }
        }
        mBinding.rv.adapter = adapter
        mBinding.rv.addItemDecoration(LeftRightItemDecoration(10.dp))
        registerAuthChange {
            //如果没有广告id则广告按钮直接不显示
            mBinding.ad.isVisible = Ad.DailySign.enable() && UserManager.isVip()
        }

        lifecycleScope.launchSafety {
            viewModel.signFlow.collect {
                res = it
                adapter.update(it)
            }
        }
        mBinding.claim.clickable {
            sign()
        }

        mBinding.ad.clickable {
            signWithAd()
        }

        viewModel.requestDailySign()
    }

    fun sign() {
        if (res?.checked == true) {
            showToast(getString(R.string.has_signed))
            return
        }
        viewModel.checkDailySign(0) {
            UserManager.refreshAuth()
            it?.let {
                saveSignToday()
                showToast(
                    getString(
                        R.string.sign_success,
                        (it.getOrDefault("point", 0)).toString()
                    )
                )
                finish()
            }
        }
    }

    private fun signWithAd() {
        if (res == null) {
            return
        }
        if (res?.checked == true) {
            showToast(getString(R.string.has_signed))
            return
        }

        lifecycleScope.launchWithLoading {
            withTimeoutOrNull(15000){
                Ad.DailySign.load()?.join()
            }
            showReword(Ad.DailySign) {
                if (it) {
                    lifecycleScope.launchSafety() {
                        viewModel.checkDailySign(1){
                            UserManager.refreshAuth()
                            it?.let {
                                saveSignToday()
                                showToast(
                                    getString(
                                        R.string.sign_success,
                                        (it.getOrDefault("point", 0)).toString()
                                    )
                                )
                                finish()
                            }
                        }
                    }
                }
            }
        }
    }


    companion object {
        fun showDialog(activity: FragmentActivity,
                       launcher: ActivityResultLauncher<Intent>,
                       doOnNext: () -> Unit) {
            if (!isToday(KVStore.signShowToday) && !hasSignedToday()) {
                saveSignShowToday()
                val intent = Intent(activity, SignDialog::class.java)
                launcher.launch(intent)
            } else {
                doOnNext.invoke()
            }
        }
    }

}

class SignAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    var rsp: SignResponse? = null
    val list = mutableListOf<SignBean>()
    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(p0.context)
        return if (p1 == 0) {
            DailySignViewHolder(ItemDailySignBinding.inflate(inflater, p0, false))
        } else {
            DailySignLandViewHolder(ItemDailySignLandBinding.inflate(inflater, p0, false))
        }
    }

    override fun onBindViewHolder(p0: RecyclerView.ViewHolder, p1: Int) {
        if (list.isNotEmpty()) {
            val data = list[p1]
            when (p0) {
                is DailySignViewHolder -> p0.update(data, p1)
                is DailySignLandViewHolder -> p0.update(data, p1)
            }
        }
    }

    override fun getItemCount(): Int {
        return 7
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == 6) 1 else 0
    }

    fun update(daily: SignResponse) {
        rsp = daily
        list.clear()
        list.addAll(daily.getRealList())
        notifyDataSetChanged()
    }

    inner class DailySignViewHolder(val binding: ItemDailySignBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun update(bean: SignBean, position: Int) {
            binding.apply {
                bean.let {
                    flChecked.isVisible = it.checked == true
                    clContainer.isSelected = it.isToday(rsp)
//                    "+${it.reward}".also { tvCount.text = it }
                    val spannedDayText = buildSpannedString {
                        val dayText = "+"
                        // 先添加字体大小为 20 的部分
                        append(dayText)
                        setSpan(
                            AbsoluteSizeSpan(16, true),
                            0,
                            dayText.length,
                            SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        // 再添加一个空格
                        append(" ")
                        // 接着添加字体大小为 26 的部分
                        val extraText = it.reward.toString()
                        val start = length
                        append(extraText)
                        setSpan(
                            AbsoluteSizeSpan(26, true),
                            start,
                            start + extraText.length,
                            SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                    }
                    tvCount.text = spannedDayText
                    val dayText = String.format(Locale.getDefault(), "%02d", position + 1)
                    tvDay.text = dayText
                }

            }
        }
    }

    inner class DailySignLandViewHolder(val binding: ItemDailySignLandBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun update(bean: SignBean, position: Int) {
            binding.apply {
                bean.let {
                    flChecked.isVisible = it.checked == true
                    clContainer.isSelected = it.isToday(rsp)
                    "+${it.reward}".also { tvCount.text = it }
                    val spannedDayText = buildSpannedString {
                        val dayText = "+"
                        // 先添加字体大小为 20 的部分
                        append(dayText)
                        setSpan(
                            AbsoluteSizeSpan(16, true),
                            0,
                            dayText.length,
                            SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        // 再添加一个空格
                        append(" ")
                        // 接着添加字体大小为 26 的部分
                        val extraText = it.reward.toString()
                        val start = length
                        append(extraText)
                        setSpan(
                            AbsoluteSizeSpan(26, true),
                            start,
                            start + extraText.length,
                            SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                    }
                    tvCount.text = spannedDayText
                    val dayText = String.format(Locale.getDefault(), "%02d", position + 1)
                    tvDay.text = dayText
                }
            }
        }

    }
}


class LeftRightItemDecoration(private val space: Int) : ItemDecoration() {
    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
// 获取当前 item 的位置
        val position = parent.getChildAdapterPosition(view)
        if (position < 6) {
            // 获取列数
            val spanCount = (parent.layoutManager as? GridLayoutManager)?.spanCount ?: 1

            // 计算当前 item 所在的列
            val column = position % spanCount

            // 设置左右间距
            outRect.left = space - column * space / spanCount
            outRect.right = (column + 1) * space / spanCount

            // 设置上下间距
            if (position >= spanCount) {
                outRect.top = space
            }
        }
    }
}